#!/usr/bin/env python
# -*- coding: utf-8; py-indent-offset:4 -*-
###############################################################################
# 单均线55, 均线之上买入, 均线之下卖出
###############################################################################
from __future__ import (absolute_import, division, print_function,
                        unicode_literals)

# import pyfolio as pf
import backtrader as bt
import backtrader.indicators as btind
from backtrader.utils.datehelper import *
from example.backtest.btrun import BtRun
from example.backtest.strategybase import StrategyBase


class MaSingleStrategy(StrategyBase):
    alias = ('01_ma_single_strat',)

    params = (
        ('period', 55),
    )

    def __init__(self):
        # 这里的指标会自己通过owner注册到策略之上
        super(MaSingleStrategy, self).__init__()
        self.ma = btind.SMA(self.data.close, period=self.p.period)

    def log(self, txt, dt=None):
        ''' Logging function fot this strategy'''
        pass
        print('%s, %s' % (bt.utils.num2date(dt).strftime("%Y-%m-%d %H:%M"), txt))

    def next(self):

        dtstr = date2str(self.data.datetime.datetime())

        close = self.data.close[0]
        if close > self.ma[0] and self.position.size == 0:
            self.order = self.buy(self.data, exectype=bt.Order.Market)

        if close < self.ma[0] and self.position.size > 0:
            self.order = self.close(self.data, exectype=bt.Order.Market)

        i = list(range(0, len(self.datas)))
        for (d, j) in zip(self.datas, i):
            if len(d) == d.buflen() - 1:
                last_order_dt = date2str(bt.utils.num2date(self.order.created.dt)) if self.order else None
                if self.position.size != 0 and dtstr != last_order_dt:
                    self.close(d, exectype=bt.Order.Market)


if __name__ == '__main__':
    kwargs = {
        'workspace': '/Users/wudi/Workspace/fund/workspace',
        'symbol': 'ETH/USDT',
        'strat': '01_ma_single_strat',
        'params': {'period': 55},
        'start': '2019-09-01',
        'end': '2021-10-18',
        'tf': '1h',
        'benchmark': None,
        'filter_exp': None,
        'resample': None,
        'cash': 10000,
        'comm': 0.0003,
        'size': 90,
        'opt': False,
        'plot': False
    }
    BtRun().run(**kwargs)
